<template>
  <div class="embed-chat-container" :data-theme="isDarkMode ? 'dark' : 'light'">
    <!-- 加载状态 -->
    <div v-if="isInitializing" class="loading-container">
      <div class="loading-content">
        <el-icon class="loading-icon is-loading">
          <Loading />
        </el-icon>
        <p>正在初始化聊天窗口...</p>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="hasError" class="error-container">
      <div class="error-content">
        <el-icon class="error-icon">
          <Warning />
        </el-icon>
        <h3>{{ errorMessage }}</h3>
      </div>
    </div>

    <!-- 聊天界面 -->
    <div v-else class="chat-layout">
      <!-- 顶部标题栏 -->
      <div class="chat-header" style="display: none">
        <div class="header-left">
          <h3>析语AI数据分析</h3>
          <span v-if="currentDataset" class="dataset-info">
            数据集: {{ currentDataset.name }}
          </span>
          <span
            v-else-if="historyDialogs.length > 0 && historyDialogs[0].dataset_ids"
            class="dataset-info"
          >
            数据集ID: {{ historyDialogs[0].dataset_ids }}
          </span>
        </div>
        <div class="header-right">
          <el-button
            :icon="isDarkMode ? Sunny : Moon"
            circle
            @click="toggleTheme"
            class="theme-toggle"
            title="切换主题"
          />
        </div>
      </div>

      <!-- 聊天区域 -->
      <ChatAreaV1
        ref="chatAreaRef"
        :isDarkMode="isDarkMode"
        :currentDataset="currentDataset"
        :datasetFields="datasetFields"
        :showDatasetSelector="true"
        :defaultDatasetId="defaultDatasetId"
        @start-new-chat="handleStartNewChat"
        @create-new-dataset="handleCreateNewDataset"
        @refresh-data="handleRefreshData"
        @dialog-loaded="handleDialogLoaded"
        class="embed-chat-area"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading, Warning, Moon, Sunny } from '@element-plus/icons-vue'
import ChatAreaV1 from '../components/layout/ChatAreaV1.vue'
import { setToken } from '../api/auth'
import request  from '../api/config'

// 路由相关
const route = useRoute()

// 专用的getTempSession函数，使用嵌入式请求实例
const getTempSessionForEmbed = (dataset_id = '') => {
  return request({
    url: '/dk/sessions/get_temp_session',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Accept: 'application/json',
    },
    data: { dataset_id },
  })
}

// 状态管理
const isInitializing = ref(true)
const hasError = ref(false)
const errorMessage = ref('')
const currentDataset = ref(null)
const datasetFields = ref([])
const historyDialogs = ref([])
const currentDialogId = ref(null)
const chatAreaRef = ref(null)
// 默认数据集ID，从会话中获取
const defaultDatasetId = ref(null)

// 主题管理
const isDarkMode = ref(localStorage.getItem('theme') === 'light' ? false : true)

// 切换主题
const toggleTheme = () => {
  isDarkMode.value = !isDarkMode.value
  localStorage.setItem('theme', isDarkMode.value ? 'dark' : 'light')

  const htmlEl = document.documentElement
  if (isDarkMode.value) {
    htmlEl.classList.add('dark')
    document.body.setAttribute('class', 'el-dark-mode')
    document.documentElement.style.setProperty('--el-color-primary', '#409EFF')
  } else {
    htmlEl.classList.remove('dark')
    document.body.removeAttribute('class')
    document.documentElement.style.removeProperty('--el-color-primary')
  }
}

// 初始化聊天窗口
const initializeChatWindow = async () => {
  try {
    isInitializing.value = true
    hasError.value = false

    // 获取URL参数
    const urlToken = route.query.token
    const datasetId = route.query.dataset_id

    // 验证token
    if (!urlToken) {
      throw new Error('缺少访问令牌，请检查链接是否正确')
    }

    // 设置token
    setToken(urlToken)

    // 使用 get_temp_session 接口获取或创建临时会话
    const tempSessionResult = await getTempSessionForEmbed(datasetId)

    if (!tempSessionResult || !tempSessionResult.success) {
      throw new Error('获取临时会话失败')
    }

    // 创建会话对象
    const session = {
      id: tempSessionResult.session_id,
      title: tempSessionResult.session_title,
      type: 'chat',
      starred: false,
      messages: [],
      dataset_ids: tempSessionResult.dataset_id,
    }

    // 设置默认数据集ID
    defaultDatasetId.value = tempSessionResult.dataset_id

    // 设置会话列表（仅包含当前会话）
    historyDialogs.value = [session]
    currentDialogId.value = session.id

    // 显示会话状态信息
    if (tempSessionResult.is_new) {
      ElMessage.success(`已创建新会话: ${tempSessionResult.session_title}`)
    } else {
      ElMessage.info(`已加载会话: ${tempSessionResult.session_title}`)
    }

    // 初始化完成
    isInitializing.value = false

    // 加载会话消息
    await loadTargetSession(session)
  } catch (error) {
    console.error('初始化聊天窗口失败:', error)
    hasError.value = true

    // 处理不同类型的错误
    if (error.response?.status === 401 || error.response?.status === 403) {
      errorMessage.value = '访问令牌无效或已过期，请重新获取链接'
    } else if (error.response?.data?.detail === 'Unauthorized') {
      errorMessage.value = '访问令牌无效或已过期，请重新获取链接'
    } else if (error.message === 'Unauthorized') {
      errorMessage.value = '访问令牌无效或已过期，请重新获取链接'
    } else if (error.message) {
      errorMessage.value = error.message
    } else {
      errorMessage.value = '初始化失败，请稍后重试'
    }
    isInitializing.value = false
  }
}

// 加载目标会话
const loadTargetSession = async (session) => {
  try {
    currentDialogId.value = session.id

    // 确保ChatAreaV1组件已经渲染
    await nextTick()

    // 更新ChatAreaV1组件的对话列表
    if (chatAreaRef.value) {
      chatAreaRef.value.historyDialogs = historyDialogs.value
      await chatAreaRef.value.loadDialogMessages(session)
    } else {
      console.warn('ChatAreaV1组件尚未渲染，无法加载会话')
    }
  } catch (error) {
    console.error('加载会话失败:', error)
    ElMessage.error('加载会话失败')
  }
}

// 处理对话加载完成事件
const handleDialogLoaded = ({ status }) => {
  // 设置当前数据集
  if (status && status.dataset) {
    currentDataset.value = status.dataset
  }
}

// 处理开始新对话（在嵌入式窗口中禁用）
const handleStartNewChat = () => {
  ElMessage.info('嵌入式窗口不支持创建新对话')
}

// 处理创建新数据集（在嵌入式窗口中禁用）
const handleCreateNewDataset = () => {
  ElMessage.info('嵌入式窗口不支持创建新数据集')
}

// 处理刷新数据
const handleRefreshData = async () => {
  try {
    ElMessage.info('正在刷新数据...')

    if (currentDialogId.value) {
      const session = historyDialogs.value.find((d) => d.id === currentDialogId.value)
      if (session) {
        await loadTargetSession(session)
        ElMessage.success('数据已刷新')
      } else {
        // 如果找不到当前会话，重新初始化
        await initializeChatWindow()
      }
    } else {
      // 如果没有当前会话，重新初始化
      await initializeChatWindow()
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新失败: ' + (error.message || '未知错误'))
  }
}

// 页面挂载时初始化
onMounted(async () => {
  // 初始化主题
  const savedTheme = localStorage.getItem('theme')
  if (savedTheme) {
    isDarkMode.value = savedTheme === 'dark'
  } else {
    isDarkMode.value = true // 默认暗色主题
    localStorage.setItem('theme', 'dark')
  }

  // 应用主题
  const htmlEl = document.documentElement
  if (isDarkMode.value) {
    htmlEl.classList.add('dark')
    document.body.setAttribute('class', 'el-dark-mode')
    document.documentElement.style.setProperty('--el-color-primary', '#409EFF')
  } else {
    htmlEl.classList.remove('dark')
    document.body.removeAttribute('class')
    document.documentElement.style.removeProperty('--el-color-primary')
  }

  await initializeChatWindow()
})
</script>

<style scoped>
.embed-chat-container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 加载状态 */
.loading-container,
.error-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.loading-content,
.error-content {
  text-align: center;
  max-width: 400px;
}

.loading-icon {
  font-size: 48px;
  color: var(--el-color-primary);
  margin-bottom: 16px;
}

.error-icon {
  font-size: 48px;
  color: var(--el-color-danger);
  margin-bottom: 16px;
}

.loading-content p,
.error-content h3 {
  margin: 0;
  color: var(--app-text-primary);
  font-size: 16px;
}

.error-content h3 {
  margin-bottom: 20px;
  font-size: 18px;
}

/* 聊天布局 */
.chat-layout {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部标题栏 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: var(--app-card-bg, #ffffff);
  border-bottom: 1px solid var(--app-border-color, #e5e7eb);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left h3 {
  margin: 0;
  font-size: 18px;
  color: var(--app-text-primary);
  font-weight: 600;
}

.dataset-info {
  font-size: 12px;
  color: var(--app-text-secondary);
  margin-top: 2px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.theme-toggle {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.theme-toggle:hover {
  transform: scale(1.1);
}

/* 聊天区域 */
.embed-chat-area {
  flex: 1;
  overflow: hidden;
  border: none;
  border-radius: 0;
}

/* 暗色模式样式 */
:global(.dark-mode) .embed-chat-container {
  background: var(--app-background, #1a1a1a);
}

:global(.dark-mode) .chat-header {
  background: var(--app-card-bg, #2d2d2d);
  border-bottom-color: var(--app-border-color, #404040);
}

:global(.dark-mode) .loading-content p,
:global(.dark-mode) .error-content h3 {
  color: var(--app-text-primary, #e5e7eb);
}

/* 确保聊天区域在嵌入式窗口中正确显示 */
:deep(.main-content) {
  border-radius: 0;
  border: none;
  box-shadow: none;
}

:deep(.chat-container) {
  border-radius: 0;
}

:deep(.content-tabs-header) {
  display: none; /* 隐藏标签页头部 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    padding: 10px 15px;
  }

  .header-left h3 {
    font-size: 16px;
  }

  .theme-toggle {
    width: 32px;
    height: 32px;
  }
}
</style>
